<template>		<!--该页面为测试记录页面-->
	<div>
		<el-breadcrumb separator="/"> <!--面包屑 -->
      <el-breadcrumb-item><i class="el-icon-s-home" style="margin-right: 15px;font-size: 16px"></i>模板管理</el-breadcrumb-item>
    </el-breadcrumb>
		<div class="info">
		
			<el-card shadow="always"  class="box-card">
				<div slot="header" class="clearfix">
					<el-row>
						<el-col :span="7">
							<div class="inputText"><span style="margin-right: 15px;">模板名称</span>
								<el-input placeholder="请输入模板名称" v-model="searchContent.templateName" clearable size="medium" style="width:200px" ></el-input>
							</div>
						</el-col>
						<el-col :span="7" :offset="3">
							<div class="inputText" ><span style="margin-right: 15px;">模板类型</span>
								<el-select v-model="searchContent.templateType" clearable placeholder="请选择" size="medium">
									<el-option
										v-for="item in typeLIst"
										:key="item.value"
										:label="item.label"
										:value="item.value"
										>
									</el-option>
								</el-select>
							</div>
						</el-col>
						<el-col :span="4" :offset="3">
							<div style="float: right" >
								<el-button type="primary"  @click="toSerach" size="small">查询</el-button>
							</div>	
						</el-col>
					</el-row>	
				</div>
				<el-row>
					<el-button type="text" class="global_add" style="float:right; margin-right: 15px;margin-bottom: 5px;" :disabled="btnList.upload" @click="dialogVisible = true" size="small" >↑&nbsp;上传模板</el-button>
					<el-dialog title="上传模板" :visible.sync="dialogVisible" width="450px" :modal="false" :before-close="handleClose">
						<el-form  label-width="68px" :model="upData"  ref="upload">
							<el-form-item label="模板类型" >
								<el-select v-model="upData.templateType" placeholder="请选择模板类型" clearable size="medium" style="width:90%">
									<el-option v-for="item in typeLIst" :key="item.value" :label="item.label" :value="item.value" ></el-option>
								</el-select>
            	</el-form-item>
						</el-form> 
						<el-upload
							class="upload-demo"
							ref="upload"
							drag
							action="http://192.168.10.100:8010/templateManagement/uploadTemplate"
							:auto-upload="false"
							:on-remove="handleRemove"
							:data="upData"
							:before-upload="beforeUpload"
							:on-success="handleSuccess"
							accept=".doc,.docx"
							:on-error="handleError"
							:on-change="filesChange"
							:on-exceed="handleExceed"
							:limit="1"
							>							
							<div class="el-upload__text" >单击选择文件</div>
							<div class="el-upload__text" >支持上传的文件格式: .doc .docx</div>
							<div class="el-upload__text" >仅支持单个文件上传</div>
							<div class="el-upload__text" style="color:#D9001B;">所上传模板会覆盖该类型原有模板</div>
         		</el-upload>
						<!-- <el-row>
							<el-col>
								<div style="float:right; margin-top: 10px">
								<el-button class="variableCanelButton" @click="cancelUpload">取 消</el-button>
								<el-button  type="primary" :disabled="uploadSuccess" @click="affirmDialog">确定</el-button>
								</div>
							</el-col>
          </el-row>  -->
		  <span slot="footer" class="dialog-footer">
            <el-button class="variableCanelButton textBtn" @click="cancelUpload">取 消</el-button>
								<el-button  type="primary" :disabled="uploadSuccess" @click="affirmDialog">确定</el-button>
        </span>
        	</el-dialog>
				</el-row>
				<el-table stripe v-loading="dataLoading" :data="templateData.slice((currentPage-1)*pagesize,currentPage*pagesize)" ref="multipleTable" style="width: 100%">
					<el-table-column type="index" :index = '(index) =>{return (index + 1) + (currentPage - 1) * pagesize}' label="#" width="70" align="center"></el-table-column>
					<el-table-column align="center" prop="tpl_name" label="模板名称" show-overflow-tooltip></el-table-column>
					<el-table-column align="center" prop="tpl_kind" label="模板类型" show-overflow-tooltip :formatter="formatter"></el-table-column>
					<el-table-column align="center"  label="操作" >
						<template slot-scope="scope">
              <el-button class="global_edit" @click="preview(scope.$index, scope.row)" type="text" size="small">预览</el-button>
							<el-button class="global_dowlond" type="text" size="small" @click="downLoad(scope.$index, scope.row)" style="color:#6C59DD" >下载</el-button>
							<el-button class="global_delete" type="text" size="small" :disabled="btnList.delete" @click="toDeleteTemplate(scope.$index, scope.row)" style="color:#D9001B" >删除</el-button>
						</template> T
					</el-table-column>
				</el-table>
				<el-pagination class="pagination" background :hide-on-single-page="showPagination" :current-page.sync="currentPage" @size-change="handleSizeChange" :page-size="pagesize" layout="prev, pager, next" :total="templateData.length"></el-pagination>
			</el-card>
		</div>
	</div>
</template>
<script>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 引入需要用到的第三方nodejs库，如日期计算等
// 需要先通过npm安装第三方组件包，然后在代码中使用
// npm install xxx 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
import moment from 'moment';
import dayjs from 'dayjs';
import sessionStorage from '../../public/storage.js';
import roleBtn from '../../public/means'
export default {
	data() {
		return {
			dialogVisible: false,		
			menu_id: 21,
      btnList: {
        upload: false,
        delete: false,
      },		
			searchContent: {
				templateName :'',
				templateType:'',
			},	//搜索
			templateData: [],
			templateType:'',
			typeLIst:[
				{value: '1',label: '点检记录'},
				{value: '2',label: '工频试验报告'},
				{value: '3',label: '雷电试验报告'},
				{value: '4',label: '局放试验报告'}
			],
			upData:{
				templateType:''
			},
			uploadSuccess:false,
			showPagination: true,
			currentPage: 1,
      pagesize: 10,
			fileCount:0,
			dataLoading: false,
		};
	},
	methods: {
		/**
		 * 表格数据，模板类型数据格式化
		 */
		formatter(row, column){
			switch(row.tpl_kind){
				case 1:
					return "点检记录";break;
				case 2:
					return "工频试验报告";break;
				case 3:
					return "雷电试验报告";break;
				case 4:
					return "局放试验报告";break;
			}
		},
		affirmDialog(files,fileList){

			if(this.upData.templateType==''){
				this.$message.closeAll();
				this.$message.warning(`请选择模板类型`);
			}else if(this.fileCount==0){
				this.$message.closeAll();
				this.$message.warning(`请选择模板文件`);
			}else{
				console.info("123")

				this.uploadSuccess=true;
				this.$refs.upload.submit();
			}
		},
		cancelUpload(){
			this.dialogVisible = false;
		},
		handleRemove(){},
		beforeUpload(file){
			// if(file.name == 'image.docx'){
			// 	this.$message.closeAll();
			// 	this.$message.warning(`请选择文件`);
			// }
			
			
		},
			//文件上传成功
    handleSuccess(res, file, fileList) {
      if(res.code === 200){
        this.$message({message: '文件上传成功!', type: 'success', duration: 1000 });
				this.dialogVisible=false;
        this.clearFiles();
				this.upData.templateType='';
        this.getAllTemplate();
				this.uploadSuccess=false;
      }
    },
		handleError(){},
		filesChange(file, fileList){
			let type = file.name.split(".")[1]
			if (type !== 'docx' && type !== 'doc') {
				this.clearFiles();
				this.$message.warning(`请选择 .docx或 .doc格式的文件`);
			} else {
				this.fileCount=fileList.length;
			}
			
		},
		//超出文件定义个数
		handleExceed(files, fileList) {
			this.$message.closeAll();
			this.$message.warning(`当前限制选择 1 个文件`);
		},
		handleClose(){
			this.dialogVisible=false;
		},
		clearFiles(){
			this.$refs['upload'].clearFiles();
		},
		toSerach(){
			this.getAllTemplate();
		},
		toDeleteTemplate(index,row){
			this.$confirm('确定删除该模板,此操作不可撤销', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(({ result }) => {
        if(!result){
					this.deleteTemplate(row.tpl_id,row.tpl_name);
				}
      }).catch(() => {
        });
		},
		async deleteTemplate(templateId,templateName){
			const params = {
        templateId:templateId,
				templateName:templateName
      }
			const ret = await this.$http.delete("/templateManagement/deleteTemplate",{params,});
      if(ret.code === 200){
      this.$message({
          showClose: true,
          message: ret.message,
          type: 'success'
        });
      }
			this.getAllTemplate();
		},
		async previewAndGenerateFile(instrName,instrId,timeSelect){
			const params = {
				'instrName': instrName,
				'instrId':instrId,
				'timeSelect':timeSelect
			}
			const res =  await this.$http.post("/checkRecord/writeReport",params);
			return res;
		},
    async preview(index,row){
			var url = "1http://192.168.10.100:8010/public/template/"+row.tpl_name;
			window.open("http://192.168.10.100:8012/onlinePreview?url=" + encodeURIComponent(url)); 
		},
		async downLoad(index,row){
			location.href = 'http://192.168.10.100:8010/public/template/'+row.tpl_name ;
		},
		handleSizeChange(val) {
      this.pagesize=val;
		},
		
		//获取所有模板
		async getAllTemplate(){
			this.dataLoading = true;
			const params = {
        'templateName': this.searchContent.templateName,
				'templateType':this.searchContent.templateType
      }
			const ret = await this.$http.get("/templateManagement/getAllTemplate",{params,});
			this.templateData=ret.result;
			this.dataLoading = false;
		},
	},
	mounted() {
		
		this.getAllTemplate();
		
	},
  async created() {
    const role_id = JSON.parse(sessionStorage.getItem('userInfo')).role_id;
      if(role_id){
      // 获取按钮权限状态
      let arr = await roleBtn.roleBtnList(role_id, this.menu_id)
      this.btnList = arr
    }
  }
};
</script>
<style lang="scss" scoped>
@import "./TemplateManagement.scss";
</style>